#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-10-10'
# code is far away from bugs with the god animal protecting ~
"""
import re

from rest_framework import serializers
from rest_framework.response import Response

import constants
from address.models import Address


class AddressGetSerializer(serializers.ModelSerializer):
	city_id = serializers.IntegerField(write_only=True)
	district_id = serializers.IntegerField(write_only=True)
	province_id = serializers.IntegerField(write_only=True)

	province = serializers.StringRelatedField(read_only=True)
	city = serializers.StringRelatedField(read_only=True)
	district = serializers.StringRelatedField(read_only=True)

	def create(self, validated_data):
		user = self.context['request'].user

		if user.addresses.count() >= constants.USER_ADDRESS_COUNTS_LIMIT:
			return Response({'message':'用户保存地址数量超限'},status=400)

		validated_data['user'] = user
		return super().create(validated_data)

	class Meta:
		model = Address
		fields = '__all__'
		# exclude = ['create_time', 'update_time', ]
		read_only_fields = ['user']


	def validate_mobile(self, value):
		if not re.match(r'^1[3-9]\d{9}$', value):
			raise serializers.ValidationError('手机号格式错误')
		return value


class AddressChangeTitleSerializer(serializers.ModelSerializer):

	class Meta:
		model = Address
		fields = ['title']
